// pages/flea/mySend/index.js
var app = getApp(), fetchApi = require("../../../../utils/httpPost.js"), common_Js = require("../../../../component/common.js");

import Toast from '../../../../component/vant/toast/toast';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    questionList:[],
    pageIndex:1,
    pageSize:10,
    loading: false,
    netWork: true,
    isLoading: true,
    netWork:false,
    hasData:false,
    survey_id:0,
    answer_json:[],
    submitState:false,
    survey:{},
    taskId:0,
    fileList1:[],
    user_id:0,
    targetId:0,
    roomCount:0,
    statement:{},//声明
    checkboxXieyi:false,
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('问卷 options',options)
    var that = this;
    var isLogin = app.getStorageSync("isLogin");
    if(isLogin == 0){
      wx.navigateTo({
        url: '/pages/login/index',
      })
    }else{
    }

    if(options.q){
      var q = decodeURIComponent(options.q) // 获取到二维码原始链接内容
      const scancode_time = parseInt(options.scancode_time) // 获取用户扫码时间 UNIX 时间戳
      
      q = "?" + q.split("?")[1];
      this.data.query = q;
      console.log('q',q)
      options = common_Js.getQueryVariable(q);
      console.log('options',options)
      var id = parseInt(options.id) 
      that.data.survey_id = id
    }

    if(options.id){
      this.data.survey_id = parseInt(options.id);
    }
    if(options.taskId){
      this.data.taskId = parseInt(options.taskId);
    }
    if(options.targetId){
      this.data.targetId = parseInt(options.targetId);
    }
    
    this.data.user_id = app.getStorageSync('user_id');
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.initRequest()
  },
  initRequest(){
    var that = this;
    that.data.pageIndex = 1;
    that.setData({
      loading: false,
      netWork: false,
      isLoading: true,
      hasData:false,
      questionList:[]
    });
    that.onHttpInit()
  },
  /**
   * 获取页面数据的 http请求
   */
  onHttpInit: function () {
    var that = this;
    fetchApi.httpPost('/survey/question/list', {
      survey_id:this.data.survey_id, 
      pageSize: that.data.pageSize,
      pageIndex: that.data.pageIndex,
      fromType:0,// 问卷模板
    }, function (res) {
      if (res.data.code == 0) {
        that.setData({
          roomCount: res.data.data.roomCount,
        })
        that.data.statement = res.data.data.statement;
        if(res.data.data.statement != undefined){
          that.setData({
            statement: res.data.data.statement,
          });
        }
        that.setData({
          hasData: true,
          survey: res.data.data.survey,
        });
        
        if(res.data.data.survey.surveyType == 0){
          wx.setNavigationBarTitle({
            title: '问卷内容',
          })
        }
        else if(res.data.data.survey.surveyType == 1){
          wx.setNavigationBarTitle({
            title: '模板内容',
          })
        }
        else if(res.data.data.survey.surveyType == 2){
          wx.setNavigationBarTitle({
            title: '标准内容',
          })
        }

        if (res.data.totalcount > 0) {
          that.data.pageIndex += 1;
          console.log("问卷调查列表", res)
          var questions = res.data.data.questions;
          console.log('questions',questions)
          if(questions.length > 0){
            for (var index in questions) {
              that.data.questionList.splice(that.data.questionList.length, 0, questions[index]);
            }
            console.log('that.data.questionList',that.data.questionList)
            that.setData({
              hasData: true,
              questionList: that.data.questionList
            })
          }
        }
      }
      that.setData({
         isLoading: false, loading: true, netWork: true,
      })
    }, function (res) {
        that.setData({ hasData: false,  isLoading: false,  loading: true, netWork: true })
    })
    wx.hideNavigationBarLoading() //完成停止加载
    wx.stopPullDownRefresh() //停止下拉刷新
  },
  onChangeCheckBox(e){
    console.log('onChangeCheckBox',e)
    this.data.checkboxXieyi = e.detail;
    this.setData({
      checkboxXieyi: this.data.checkboxXieyi
    })
  },
  goNotice1(e){
    wx.navigateTo({
      url: '/pages/notice/detail/index?is_sign=0&id=' +  this.data.statement.noticeId,
    })
  },
  questionDetail(res){
    console.log('questionDetail',res)
    var id = res.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pagesProperty/pages/survey/question/index?id='+ id,
    })
  },
  onChangeAnswer(val){
    console.log('onChangeAnswer',val)
    var answer_index = val.detail;//选择答案的索引  选择了第几个
    var question_index= val.currentTarget.dataset.index;
    var setions = this.data.questionList[question_index].sections;
    for(var index in setions){
      this.data.questionList[question_index].sections[index].check = '';
    }
    console.log('this.data.questionList======11',this.data.questionList)
    this.data.questionList[question_index].sections[answer_index].check = 1;
    console.log('this.data.questionList======22',this.data.questionList)
  },
  inputSection(e){
    console.log('inputSection',e)
    var index = e.currentTarget.dataset.index;
    var json = { value:  e.detail,check:'' }
    
    console.log('inputSection sections',this.data.questionList[index])
    this.data.questionList[index].sections[0] = json;
  },
  validateAnswer(){
    var answer_count = 0;
    for(var index in this.data.questionList){
      var bl = false;
      var question = this.data.questionList[index];
      console.log('question',question)
      var sections = question.sections;
      console.log('sections',sections)

      if(question.questionType == 0){//选择项
        if(sections.length > 0){
          for(var s_index in sections){
            var check = sections[s_index].check + '';
            if(check != ''){
              console.log('validateAnswer',question.question)
              bl = true;
              break;
            }
          }
        }
      } else if(question.questionType == 1){//输入项
        if(sections.length > 0){
          if(sections[0].value !=undefined && sections[0].value != ""){
            bl = true;
          }
        }
      } else if(question.questionType == 2){//图片
        let filePath = question.filePath;
        if(filePath.length > 0){
          bl = true;
        }
      }
      if(bl){
        answer_count++;
      }
    }
    return answer_count;
  },
  setAnswerJson(){
    var that = this;
    that.data.answer_json = [];
    for(var index in this.data.questionList){
      var question = this.data.questionList[index];
      console.log('question',question)
      var sections = question.sections;
      var jsonData = { question_id: question.id,question_type: question.questionType, check_value:-1 }
      
      if(question.questionType == 0){
        for(var s_index in sections){
          if(sections[s_index].check != ''){
            jsonData.check_value = parseInt(s_index);// sections[s_index].check;
            break;
          }
        }
      } else if(question.questionType == 1){
        jsonData.check_value = sections[0].value;
      }
      that.data.answer_json.push(jsonData)
    }
    console.log('that.data.answer_json',that.data.answer_json)
  },
  submitQuestion(val){
    var that = this;

    console.log('this.data.statement',this.data.statement)
    if(this.data.statement != undefined && this.data.statement.noticeId > 0 && !this.data.checkboxXieyi){
      Toast('请阅读并同意声明'); return;
    }


    if(this.data.submitState == true){
      Toast('已提交请稍后...'); return;
    }
    // console.log('submitQuestion',val);
    var answer_count = this.validateAnswer()
    console.log('answer_count',answer_count)
    if(answer_count < this.data.questionList.length){
      Toast.fail("有问题没有填写");
      return;
    }
    this.setAnswerJson();

    this.setData({
      submitState:true,
    })
    this.data.submitState = true;
    var answer = JSON.stringify(that.data.answer_json);
    fetchApi.httpPost('/survey/addRecord',{
      survey_id : that.data.survey_id,
      task_id : that.data.taskId,
      target_id : that.data.targetId,
      answer : answer,
    }, function (res) {
      console.log("提交问卷调查", res)
      if(res.data.code == 0){
        Toast.success(res.data.msg);
        that.setData({
          submitState: false,
        })
        that.data.submitState = false;
        var record_id = parseInt(res.data.data)
        Toast.success(res.data.msg);

        for(let indexQ in that.data.questionList){
          let question = that.data.questionList[indexQ];
          if(question.questionType == 2){
            let filePath = question.filePath;
            if (record_id > 0 && filePath.length > 0) {
              for (var index in filePath) {
                console.log(' filePath', filePath)
                wx.uploadFile({
                  url: fetchApi.getPlatformUrl() + '/survey/uploadImg',
                  filePath: filePath[index].url,
                  name: 'file',
                  formData: { 
                    record_id: record_id,
                    question_id: question.id,
                    user_id: that.data.user_id,
                    img_type: 0,
                  },
                  success: function (res) {
                    console.log('uploadFile success res', res)
                  }, fail: function (res) {
                    console.log('uploadFile fail res', res)
                  }
                })
              }
            }
          }
        }
        
        setTimeout(function(){
          wx.navigateBack({ delta: 1 });
        },1000)
      }else{
        that.setData({
          submitState: false,
        })
        that.data.submitState = false;
        Toast.fail(res.data.msg);
      }
    },function(){})
  },
  goAddRoom(){
    wx.navigateTo({
      url: '/pagesProperty/pages/feeOrder/index',
    })
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作  下拉刷新
   */
  onPullDownRefresh: function () {
    this.initRequest(this.data.currentTab)
  },
  deleteImg:function(res){
    console.log('删除图片', res)
    var imgIndex = res.detail.index;//选择的图片的索引
    console.log('imgIndex', imgIndex)
    // 问题索引
    var index = res.currentTarget.dataset.index;
    console.log('index', index)
    // let fileList = this.data.questionList[index].filePath;
    // console.log('fileList',fileList)
    this.data.questionList[index].filePath.splice(imgIndex, 1);

    this.setData({
      questionList: this.data.questionList
    });
  },
  afterRead(event) {
    var index = event.currentTarget.dataset.index;
    console.log('afterRead',event)
    const { file, name } = event.detail;
    console.log('afterRead name',name)
    console.log('afterRead file',file)

    var index = event.currentTarget.dataset.index;
    let fileList = this.data.questionList[index].filePath;

    console.log('fileList',fileList)


    this.data.questionList[index].filePath = fileList.concat(file);
    // this.setData({ [`fileList${name}`]: fileList.concat(file) });
    
    this.setData({
      questionList: this.data.questionList
    });
    // console.log('afterRead fileList',fileList)
    // this.data.fileList1.concat(file)
    console.log('this.data.questionList[index].filePath', this.data.questionList[index].filePath)
  },
  oversize() {
    wx.showToast({ title: '文件超出大小限制', icon: 'none' });
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    var that = this;
    var user_id = app.getStorageSync("user_id");
    console.log("转发成功 user_id",user_id)
    return {
      title: "精彩e家-问卷调查",
      path: '/pagesProperty/pages/survey/question/index?id='+ that.data.survey_id,
      success: function (res) {
        console.log(res, "转发成功")
      },
      fail: function (res) {
        console.log(res, "转发失败")
      }
    }
  }, 
})